<script setup lang="ts">
import { addOrganizationUser, departmentList, getAdminUserDetail, getRoleList } from '@fl/api/iam-api'
import { cloneDeep } from 'lodash-es'
import { useRule } from '../hooks/use-rule'
import { useTable } from '../hooks/use-table'
import { addStaff, updateStaff } from '@fl/api/joint-api'
import { encrypt } from '@/utils/SM4'
import { active } from 'sortablejs'

const emits = defineEmits(['confirm'])
const user = defineModel('user')
console.log('🚀 ~ user:', user)

const visible = defineModel('visible', {
    type: Boolean,
    default: false,
})
const type = defineModel('type', {
    type: Boolean,
    default: false,
})
const treeData = defineModel('treeData')
const currentOrgId = defineModel('currentOrgId')
const formLabelWidth = '140px'
const { rules } = useRule()
console.log('🚀 ~ rules:', rules)

const roleOptions = ref<any>([])
const state = {
    imgUrl: '', // 头像
    phone: '', // 手机号
    userName: '', // 登录名
    userFlag: '3',
    email: '', // 邮箱
    activeState: '1', // 默认启用
    sex: '1', // 男
    password: '', // 密码
}
const form = ref<any>({ ...state, organizationId: currentOrgId.value })
console.log('🚀 ~ form:', form)

const formRef = ref()
const orgRef = ref()
const loading = ref(false)

function init() {
    if (user.value?.accountUuid) {
        form.value = {
            ...form.value,
            ...user.value,
            activeState: String(user.value.activeState),
            sex: String(user.value.sex),
        }
    }
    else {
        form.value = {
            ...form.value,
            ...state,
            organizationId: currentOrgId.value,
            activeState: '1',
        }
    }
}
init()
// watch([() => user.value, () => currentOrgId.value], ([newUser, newOrgId]) => {
//     console.log('🚀 ~ watch ~ newOrgId:', newOrgId, newUser)

// }, { immediate: true })

// 角色
function getRoleListData() {
    getRoleList().then((res) => {
        console.log('role res', res)
        roleOptions.value = res.rows.reduce((pre, cur) => {
            cur.label = cur.roleName
            cur.value = String(cur.roleId)
            pre.push(cur)
            return pre
        }, [])
    })
}

// 组织机构树
// function getTreeData() {
//     departmentList({ enterprise: user.value.id }).then((res) => {
//         equityOptionsOrigin.value = cloneDeep(res.data)
//         equityOptions.value = arrayToTree(res.data, 'parentId', 'deptId')
//         console.log('tree res', equityOptions.value)
//     })
// }

async function submit() {
    const valid = await formRef.value.validate()
    if (valid) {
        console.log('form.value', form.value)
        loading.value = true
        const submitData = { ...form.value, password: encrypt(form.value.password) }
        let res = {}
        if (type.value) {
            res = await updateStaff(submitData)
        }
        else {
            res = await addStaff(submitData)
        }

        console.log('🚀 ~ addOrganization ~ res:', res)

        if (res) {
            close()
            ElMessage.success('保存成功')
            loading.value = false
            visible.value = false
            emits('confirm')
        }
        else {
            loading.value = false
            ElMessage.error('保存失败')
        }
    }
}

function close() {
    console.log('🚀 ~ close ~ close:')
    type.value = false
    formRef.value.resetFields()
    visible.value = false
    form.value = { ...state, organizationId: currentOrgId.value }
}
// orgIdChange
function orgIdChange(value) {
    const val = orgRef.value.getCheckedNodes()
    const target = val[0].data
    console.log('orgIdChange', value, target)
    form.value.organizationId = target.id
    form.value.organizationName = target.organizationName
}
</script>

<template>
    <div class="edit-user">
        <el-dialog v-model="visible"
                   :title="type ? '编辑用户' : '新增用户'"
                   width="800"
                   class="add-user-dialog"
                   @closed="close"
        >
            <el-form ref="formRef"
                     :model="form"
                     :inline="true"
                     :rules="rules"
                     label-position="right"
            >
                <el-form-item label="登录名称"
                              prop="userName"
                              :label-width="formLabelWidth"
                >
                    <el-input v-model="form.userName"
                              :disabled="type"
                              autocomplete="off"
                    />
                </el-form-item>

                <el-form-item label="用户名称"
                              prop="nickName"
                              :label-width="formLabelWidth"
                >
                    <el-input v-model="form.nickName"
                              autocomplete="off"
                    />
                </el-form-item>

                <el-form-item label="所属部门"
                              prop="organizationId"
                              :label-width="formLabelWidth"
                >
                    <el-cascader ref="orgRef"
                                 v-model="form.organizationId"
                                 :options="treeData"
                                 :props="{ label: 'organizationName', value: 'id', checkStrictly: true, multiple: false }"
                                 :show-all-levels="false"
                                 @change="orgIdChange($event)"
                    />
                </el-form-item>

                <el-form-item label="手机号"
                              prop="phone"
                              :label-width="formLabelWidth"
                >
                    <el-input v-model="form.phone"
                              autocomplete="off"
                    />
                </el-form-item>

                <el-form-item label="邮箱"
                              prop="email"
                              :label-width="formLabelWidth"
                >
                    <el-input v-model="form.email"
                              autocomplete="off"
                    />
                </el-form-item>

                <el-form-item label="用户密码"
                              prop="password"
                              :label-width="formLabelWidth"
                >
                    <el-input v-model="form.password"
                              :disabled="type"
                              :type="type ? 'password'
                                  : 'text'"
                              autocomplete="off"
                    />
                </el-form-item>

                <el-form-item label="用户性别"
                              prop="sex"
                              :label-width="formLabelWidth"
                >
                    <el-select v-model="form.sex">
                        <el-option label="男"
                                   value="1"
                        />

                        <el-option label="女"
                                   value="0"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="用户状态"
                              prop="activeState"
                              :label-width="formLabelWidth"
                >
                    <el-radio-group v-model="form.activeState">
                        <el-radio value="1">
                            正常
                        </el-radio>

                        <el-radio value="0">
                            停用
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="close">
                        取消
                    </el-button>

                    <el-button type="primary"
                               :loading="loading"
                               @click="submit"
                    >
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.edit-user {
    :deep(.el-select__wrapper) {
        width: 190px;
    }

    :deep(.el-input__wrapper) {
        width: 190px;
    }
}
</style>
